package com.faxsun.controller.offer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.common.web.controller.BroadleafAbstractController;
import org.broadleafcommerce.core.offer.domain.CustomerOffer;
import org.broadleafcommerce.core.offer.domain.Offer;
import org.broadleafcommerce.core.offer.service.OfferService;
import org.broadleafcommerce.profile.core.domain.Customer;
import org.broadleafcommerce.profile.web.core.CustomerState;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.faxsun.core.offer.service.CustomerOfferService;

@Controller
@RequestMapping("/coupon")
public class CutomerOfferController extends BroadleafAbstractController {

	protected static final Log LOG = LogFactory.getLog(CutomerOfferController.class);
	protected static String checkoutView = "checkout/checkout";
	protected static String checkoutPageRedirect = "redirect:/checkout";

	@Resource(name = "blOfferService")
	OfferService OfferService;

	@Resource(name = "fsCustomerOfferService")
	CustomerOfferService customerOfferService;

	@RequestMapping(value = "/redeem", method = RequestMethod.POST)
	public String addCustomerOffer(HttpServletRequest request, HttpServletResponse response, Model model,
			@RequestParam("coupon") String coupon) {

		Customer customer = CustomerState.getCustomer();
		Offer offer = OfferService.lookupOfferByCode(coupon);

		if (offer != null) {
			for (CustomerOffer existingOffer : customerOfferService.findCustomerOffersByCustomer(customer)) {
				if (existingOffer.getOffer().getId() == offer.getId()) {
					// CustomerOffer already redeemed.
					return getCheckoutPageRedirect();
				}
			}

			CustomerOffer customerOffer = customerOfferService.createCustomerOffer();
			customerOffer.setCustomer(customer);
			customerOffer.setOffer(offer);
			customerOfferService.saveCustomerOffer(customerOffer);
		}

		return getCheckoutPageRedirect();
	}

	public String getCheckoutView() {
		return checkoutView;
	}

	public String getCheckoutPageRedirect() {
		return checkoutPageRedirect;
	}

}
